﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
using BLL;
using System.Net.Mail;
using System.Text;
using System.Security.Cryptography;
using System.Data;
using System.ComponentModel;

/// <summary>
/// Summary description for Myfunction
/// </summary>
/// 

public static class Myfunction
{
     
  #region Thao tac file
  public static string CopyFile(HttpPostedFile file,string folder)
  {
    string fileName = System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "");
    fileName += Path.GetExtension(file.FileName);

    file.SaveAs(MyConfig.serverPath +folder +"/" + fileName);
    return fileName;
  }

  public static string UpdateFile(HttpPostedFile file, string folder, string currentFile)
  {
    File.Delete(MyConfig.serverPath + folder + "/" + currentFile);

    string fileName = System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "");
    fileName += Path.GetExtension(file.FileName);

    file.SaveAs(MyConfig.serverPath + folder + "/" + fileName);
    return fileName;
  }

  public static string CopyFile(HttpPostedFile file, string folder,string name)
  {
      string fileName = toUrlFriendly(name) + "-" + System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "");
      fileName += Path.GetExtension(file.FileName);

      file.SaveAs(MyConfig.serverPath + folder + "/" + fileName);
      return fileName;
  }

  public static string UpdateFile(HttpPostedFile file, string folder, string currentFile,string name)
  {
      File.Delete(MyConfig.serverPath + folder + "/" + currentFile);

      string fileName = toUrlFriendly(name) + "-" + System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "");
      fileName += Path.GetExtension(file.FileName);

      file.SaveAs(MyConfig.serverPath + folder + "/" + fileName);
      return fileName;
  }

  public static string CopyFileThumbnail(HttpPostedFile file, string folder)
  {
    string fileName = System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "");        
    fileName += Path.GetExtension(file.FileName);
    string name = fileName.Replace(".", "_thumb.");

    file.SaveAs(MyConfig.serverPath + folder + "/" + name);
    return name;
  }

  public static string UpdateFileThumbnail(HttpPostedFile file, string folder, string currentFile)
  {
    File.Delete(MyConfig.serverPath + folder + "/" + currentFile);

    string fileName = System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "");  
    fileName += Path.GetExtension(file.FileName);
    string name = fileName.Replace(".", "_thumb.");

    file.SaveAs(MyConfig.serverPath + folder + "/" + fileName);
    return fileName;
  }


  public static void DeleteFile(string folder, string fileName)
  {
    if (File.Exists(MyConfig.serverPath + folder + "/" + fileName))
      File.Delete(MyConfig.serverPath + folder + "/" + fileName);
  }
  #endregion

  //Loc dau tieng viet
  private static readonly string[] VietNamChar = new string[] 
    { 
        "aeouidy", 
        "áàạảãâấầậẩẫăắằặẳẵ", 
        "éèẹẻẽêếềệểễ", 
        "óòọỏõôốồộổỗơớờợởỡ", 
        "úùụủũưứừựửữ", 
        "íìịỉĩ", 
        "đ", 
        "ýỳỵỷỹ", 
    };
  public static string LocDau(string str)
  {
    if (str == null) return "";
    //Thay thế và lọc dấu từng char      
    for (int i = 1; i < VietNamChar.Length; i++)
    {
      for (int j = 0; j < VietNamChar[i].Length; j++)
        str = str.Replace(VietNamChar[i][j], VietNamChar[0][i - 1]);
    }

    str = str.Replace("á", "a");
    str = str.Replace("à", "a");
    str = str.Replace("ạ", "a");
    str = str.Replace("ả", "a");
    str = str.Replace("ã", "a");

    str = str.Replace("é", "e");
    str = str.Replace("è", "e");
    str = str.Replace("ẹ", "e");
    str = str.Replace("ẻ", "e");
    str = str.Replace("ẽ", "e");

    str = str.Replace("ó", "o");
    str = str.Replace("ò", "o");
    str = str.Replace("ọ", "o");
    str = str.Replace("ỏ", "o");
    str = str.Replace("õ", "o");

    str = str.Replace("ú", "u");
    str = str.Replace("ù", "u");
    str = str.Replace("ụ", "u");
    str = str.Replace("ủ", "u");
    str = str.Replace("ũ", "u");

    str = str.Replace("í", "i");
    str = str.Replace("ì", "i");
    str = str.Replace("ị", "i");
    str = str.Replace("ỉ", "i");
    str = str.Replace("ĩ", "i");

    str = str.Replace("ý", "y");
    str = str.Replace("ỳ", "y");
    str = str.Replace("ỵ", "y");
    str = str.Replace("ỷ", "y");
    str = str.Replace("ỹ", "y");


    return str;
  }


  public static DataTable ConvertToDataTable<T>(IList<T> data)
  {
      PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
      DataTable table = new DataTable();
      foreach (PropertyDescriptor prop in properties)
          table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
      foreach (T item in data)
      {
          DataRow row = table.NewRow();
          foreach (PropertyDescriptor prop in properties)
              row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
          table.Rows.Add(row);
      }
      return table;

  }



  public static System.Data.DataTable ListToDataTable<T>(
  System.Collections.Generic.IList<T> elements)
  {
      System.Reflection.PropertyInfo[] arrPropInfo = typeof(T).GetProperties();
      System.Data.DataTable dt = new DataTable();
      System.Data.DataRow dr;

      foreach (System.Reflection.PropertyInfo pInfo in arrPropInfo)
      {
          dt.Columns.Add(pInfo.Name, pInfo.PropertyType);
      }
      foreach (object elem in elements)
      {
          dr = dt.NewRow();
          foreach (System.Reflection.PropertyInfo pInfo in arrPropInfo)
          {
              dr[pInfo.Name] = pInfo.GetValue(elem, null);
          }
          dt.Rows.Add(dr);
      }

      return dt;
  }


  //Xoa the HTML
  public static string RemoveHTMLTags(string source)
  {

    string expn = "<.*?>";

    return System.Text.RegularExpressions.Regex.Replace(source, expn, string.Empty);
  }
  
  //Kiem tra Email hop le
  public static bool isEmailValid(string strEmail)
  {
    string pattern = "^[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
    Regex rx = new Regex(pattern, RegexOptions.IgnoreCase);
    if (!rx.IsMatch(strEmail))
    {
      return false;
    }
    return true;
  }

  //Ma hoa mat khau 
  public static string Encrypt(string strSource)
  {
    System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
    byte[] bs = System.Text.Encoding.UTF8.GetBytes(strSource);
    bs = x.ComputeHash(bs);
    System.Text.StringBuilder s = new System.Text.StringBuilder();
    foreach (byte b in bs)
    {
      s.Append(b.ToString("x2").ToLower());
    }
    return s.ToString().ToUpper();
  }

  public static string EncryptString(string Message, string Passphrase)
  {

    byte[] Results;

    System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

    // Buoc 1: Bam chuoi su dung MD5

    MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();

    byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

    // Step 2. Tao doi tuong TripleDESCryptoServiceProvider moi

    TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

    // Step 3. Cai dat bo ma hoa

    TDESAlgorithm.Key = TDESKey;

    TDESAlgorithm.Mode = CipherMode.ECB;

    TDESAlgorithm.Padding = PaddingMode.PKCS7;

    // Step 4. Convert chuoi (Message) thanh dang byte[]

    byte[] DataToEncrypt = UTF8.GetBytes(Message);

    // Step 5. Ma hoa chuoi

    try
    {

      ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();

      Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);

    }

    finally
    {

      // Xoa moi thong tin ve Triple DES va HashProvider de dam bao an toan

      TDESAlgorithm.Clear();

      HashProvider.Clear();

    }

    // Step 6. Tra ve chuoi da ma hoa bang thuat toan Base64

    return Convert.ToBase64String(Results);

  }

  public static string DecryptString(string Message, string Passphrase)
  {

    byte[] Results;

    System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

    // Step 1. Bam chuoi su dung MD5

    MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();

    byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

    // Step 2. Tao doi tuong TripleDESCryptoServiceProvider moi

    TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

    // Step 3. Cai dat bo giai ma

    TDESAlgorithm.Key = TDESKey;

    TDESAlgorithm.Mode = CipherMode.ECB;

    TDESAlgorithm.Padding = PaddingMode.PKCS7;

    // Step 4. Convert chuoi (Message) thanh dang byte[]

    byte[] DataToDecrypt = Convert.FromBase64String(Message);

    // Step 5. Bat dau giai ma chuoi

    try
    {

      ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();

      Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);

    }

    finally
    {

      // Xoa moi thong tin ve Triple DES va HashProvider de dam bao an toan

      TDESAlgorithm.Clear();

      HashProvider.Clear();

    }

    // Step 6. Tra ve ket qua bang dinh dang UTF8

    return UTF8.GetString(Results);

  }
  //Thong bao 

  public static void ThongBao(Literal literal, string strMesenge)
  {
    literal.Text = "<Script>alert('" + strMesenge + "')</Script>";
  }

  //Ham cat chuoi

  public static string SubString(string strInput, int countChar, string space)
  {
    if(strInput == "" || strInput == null) return "null";

    string kq = "";
    string[] mang = strInput.Trim().Split(' ');
    if (mang.Length <= countChar)
    {
      kq = strInput.ToString();
    }
    else
    {
      for (int i = 0; i <= countChar; i++)
      {
        kq = kq + mang[i] + " ";

      }
      kq = kq + space;
    }

    return kq;
  }

  //Ham tao url friendly

  public static string toUrlFriendly(string strName)
  {
    if (strName == "" || strName == null) return "null";

    string strTitle = strName.Trim();
    strTitle = strTitle.Trim('-');

    strTitle = strTitle.ToLower();
    char[] chars = @"$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray();
    strTitle = strTitle.Replace("c#", "C-Sharp");
    strTitle = strTitle.Replace("vb.net", "VB-Net");
    strTitle = strTitle.Replace("asp.net", "Asp-Net");

    //Loc dau tieng viet
    strTitle = LocDau(strTitle);

    //Thay dau (.) bang dau (-)
    strTitle.Replace(".", "-");

    //Thay ky tu dac biet bang dau (-)
    for (int i = 0; i < chars.Length; i++)
    {
      string strChar = chars.GetValue(i).ToString();
      if (strTitle.Contains(strChar))
      {
        strTitle = strTitle.Replace(strChar, string.Empty);
      }
    }
    //Thay the tat cac khoang trang bang 1 dau (-)
    strTitle = strTitle.Replace(" ", "-");

    //Thay the nhieu dau (-) bang 1 dau (-)
    strTitle = strTitle.Replace("--", "-");
    strTitle = strTitle.Replace("---", "-");
    strTitle = strTitle.Replace("----", "-");
    strTitle = strTitle.Replace("-----", "-");
    strTitle = strTitle.Replace("----", "-");
    strTitle = strTitle.Replace("---", "-");
    strTitle = strTitle.Replace("--", "-");

    //Trim Start and End Spaces
    strTitle = strTitle.Trim();

    //Trim "-" Hyphen 
    strTitle = strTitle.Trim('-');

    return strTitle;
  }

  public static string GenarateUrlHome(string strPageName)
  {
    return  (strPageName + ".aspx");
  }
  public static string GenarateUrlProduct(string strPrefix, string strName, string strId)
  {
      return strPrefix + "/" + toUrlFriendly(strName) + "/" + strId + ".aspx";
  }

  public static string GenarateUrlCateProd(string strPrefix, string strName, string strId)
  {
      return strPrefix + "/" + toUrlFriendly(strName) + "-" + strId +".aspx";
  }

  public static string GenarateUrlShopCart(string prefix)
  {
      return prefix + ".aspx";
  }


  public static string GenarateUrlArticle(string strPrefix, string strName, string strId)
  {
      return strPrefix + "/" + toUrlFriendly(strName) + "/" + strId + ".aspx";
  }
    //------------------------------------------------------------------
  public static string GenarateUrlHome(string strLang, string strPageName)
  {
    return (strLang + "/" + strPageName + ".aspx");
  }

 

  public static string GenarateUrlCateProd(string strLang, string strId, string strPage, string strPrefix, string strName)
  {
    return strLang +"/"+ strId + "/" + strPage + "/" + strPrefix + "/" + toUrlFriendly(strName) + ".aspx";
  }

  

  public static string GenarateUrlProduct(string strLang, string strId, string strPrefix, string strName)
  {
    return strLang + "/" + strPrefix + "/" + strId + "/" + toUrlFriendly(strName) + ".aspx";
  }

 
  public static string GenarateUrlShopCart(string prefix, string strName)
  {
    return prefix + "/" + strName + ".aspx";
  }

  public static string GenarateUrlNews(string strId, string strPrefix, string strName)
  {
      return strPrefix + "/" + strId + "/" + toUrlFriendly(strName) + ".aspx";
  }
  public static string GenarateUrlNews(string strLang, string strId, string strPrefix, string strName)
  {
    return strLang + "/" + strPrefix + "/" + strId + "/" + toUrlFriendly(strName) + ".aspx";
  }
  public static string GenarateUrlNewsCate(string strId, string strPage, string strPrefix, string strName)
  {
      return strId + "/" + strPage + "/" + strPrefix + "/" + toUrlFriendly(strName) + ".aspx";
  }

  public static string GenarateUrlNewsCate(string strLang, string strId, string strPage, string strPrefix, string strName)
  {
    return strLang + "/" + strId + "/" + strPage + "/" + strPrefix + "/" + toUrlFriendly(strName) + ".aspx";
  }

  public static string GenarateUrlBuyProduct(string strPrefix, string strId)
  {
      return strId +"/" + strPrefix + ".aspx";
  }
  public static string GenarateUrlBuyProduct(string strLang, string strPrefix, string strId)
  {
    return strLang + "/" + strId + "/" + strPrefix + ".aspx";
  }
  public static string GenarateUrlBuyProduct(string strLang, string strPrefix, string strId, string countItem, string colour, string size)
  {
    return strLang + "/" + strId + "/" + countItem + "/" + colour + "/"+ size + "/" + strPrefix + ".aspx";
  }

  
  public static string GenarateUrlArticle(string strLang, string strId, string strPrefix, string strName)
  {
    return strLang + "/" + strPrefix + "/" + strId + "/" + toUrlFriendly(strName) + ".aspx";
  }
  public static int GetVisited()
  {
    VisitedBLL data = new VisitedBLL();
    return data.GetValue();
  }

  public static void SaveVisited(int total)
  {
    VisitedBLL data = new VisitedBLL();
    data.Save(total);
  }
  public static string RandomString(int size, bool lowerCase)
  {
    StringBuilder sb = new StringBuilder();
    char c;
    Random rand = new Random();
    for (int i = 0; i < size; i++)
    {
      c = Convert.ToChar(Convert.ToInt32(rand.Next(65, 87)));
      sb.Append(c);
    }
    if (lowerCase)
      return sb.ToString().ToLower();
    return sb.ToString();

  }
 
  public static bool SendMail(string fromAddress, string fromPassWord, string fromDisplayName, string toAddress, string subject, string body)
  {
    //--Tạo mail -----------------------------------------------------|
    MailMessage msg = new MailMessage();
    msg.To.Add(toAddress);
    msg.From = new MailAddress(fromAddress, fromDisplayName,
        System.Text.Encoding.UTF8);
    msg.Subject = subject;
    msg.SubjectEncoding = System.Text.Encoding.UTF8;
    msg.Body = body;
    msg.BodyEncoding = System.Text.Encoding.UTF8;
    //--Cho phép gửi mã HTML trong mail ------------------------------|
    msg.IsBodyHtml = true;
    //--Độ ưu tiên của mail ------------------------------------------|
    msg.Priority = MailPriority.High;
    //--Chứng thực bao gồm username + password -----------------------|
    SmtpClient client = new SmtpClient();
    client.Credentials = new System.Net.NetworkCredential
    (fromAddress, fromPassWord);
    //--Cổng 587 của server SMTP Google để gửi mail-------------------|
    client.Port = 587;
    //--Địa chỉ server SMTP của google -------------------------------|
    client.Host = "smtp.gmail.com";
    //--Sử dụng mã hóa đường truyền SSL (Secure Sockets Layer)--------|
    client.EnableSsl = true;
    //--Bắt đầu quá trình gửi mail -----------------------------------|
    try { client.Send(msg); } //--Gửi mail--| 
    catch { return false; } //--Không thể gửi mail     
    return true; //--Gửi mail thành công
  }
  
  public static void GetDate()
  {
      DateTime date = DateTime.Now;
      DayOfWeek thu = date.DayOfWeek;
      string day_vn = "";
      string day_en = "";

          switch (thu)
          {
              case DayOfWeek.Monday:
                  {
                      day_vn = "Thứ hai";
                      day_en = "Monday";
                      break;
                  }
              case DayOfWeek.Tuesday:
                  {
                      day_vn = "Thứ ba";
                      day_en = "Tuesday";
                      break;
                  }
              case DayOfWeek.Wednesday:
                  {
                      day_vn = "Thứ tư";
                      day_en = "Wednesday";
                      break;
                  }
              case DayOfWeek.Thursday:
                  {
                      day_vn = "Thứ năm";
                      day_en = "Thursday";
                      break;
                  }
              case DayOfWeek.Friday:
                  {
                      day_vn = "Thứ sáu";
                      day_en = "Friday";
                      break;
                  }
              case DayOfWeek.Saturday:
                  {
                      day_vn = "Thứ bảy";
                      day_en = "Saturday";
                      break;
                  }
              case DayOfWeek.Sunday:
                  {
                      day_vn = "Chủ nhật";
                      day_en = "Sunday";
                      break;
                  }
          } 
  }
}